#!/usr/bin/python
# -*- coding=utf8 -*-
from chtozadali.core.models.groups import Group, Membership
from chtozadali.core.models.subject import Subject
from chtozadali.core.forms.groups import GroupForm
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from chtozadali.core.views.utilits import get_subjects

@login_required
def get_group_profile(request, group_id):
    try:
        g = Group.objects.get(id=group_id)
    except:
        return render(request, "group_profile_fail.html", {"subjects": get_subjects(Subject.objects.all())})
    gm = [i.user for i in g.membership_set.all()]
    gt = g.task_set.all()
    try:
        u_msh = g.membership_set.get(user=request.user)
    except:
        u_msh = False
    return render(request, "group_profile.html", {"group": g,
                                                  "group_members": gm,
                                                  "subjects": get_subjects(Subject.objects.all()),
                                                  "u_msh": u_msh,
                                                  "task_list": gt
                                                  })

@login_required
def enter_to_group(request, group_id):
    try:
        g = Group.objects.get(id=group_id)
    except:
        return render(request, "group_profile_fail.html", {"subjects": get_subjects(Subject.objects.all())})
    try:
        Membership.objects.get(user=request.user, group=g)
        return redirect("/group/id" + str(group_id))
    except:
        pass
    msh = Membership(
                        user=request.user,
                        group=g,
                        can_add_tasks=True
                    )
    try:
        msh.save()
    except:
        pass
    return redirect("/group/id" + str(group_id))

@login_required
def get_user_groups(request):
    groups = []
    memberships = Membership.objects.all().filter(user=request.user)
    for i in memberships:
        i.group.user_membership = i
        groups.append(i.group)
    return render(request, "group_list.html", {"group_list": groups,
                                               "subjects": get_subjects(Subject.objects.all())})

@login_required
def get_all_groups(request):
    groups = Group.objects.all()
    for i in groups:
        try:
            i.user_membership = i.membership_set.get(user=request.user)
        except:
            i.user_membership = False
    return render(request, "group_list.html", {"group_list": groups,
                                               "subjects": get_subjects(Subject.objects.all())})

@login_required
def exit_from_group(request, group_id):
    try:
        g = Group.objects.get(id=group_id)
    except:
        return render(request, "group_profile_fail.html", {"subjects": get_subjects(Subject.objects.all())})
    try:
        msh = Membership.objects.get(user=request.user, group=g)
    except:
        return redirect("/group/id" + str(group_id))
    try:
        msh.delete()
    except:
        pass
    return redirect("/groups/")

@login_required
def add_group(request):
    if request.method == "POST":
        gform = GroupForm(request.POST)
        if gform.is_valid():
            g = Group(
                        name=gform.cleaned_data["name"]
                     )
            g.save()
            msh = Membership(
                             user=request.user,
                             group=g,
                             is_admin=True,
                             is_creator=True,
                             can_add_tasks=True,
                             can_edit_tasks=True,
                             can_change_memberships=True
                            )
            msh.save()
            return redirect("/group/id" + str(g.id))
    else:
        gform = GroupForm()
    return render(request, "group_add.html", {"group_form": gform,
                                              "subjects": get_subjects(Subject.objects.all()),
                                             })

@login_required
def edit_group(request, group_id):
    if request.method == "POST":
        gform = GroupForm(request.POST)
        try:
            g = Group.objects.filter(id=group_id)
        except:
            return render(request, "group_profile_fail.html", {"subjects": get_subjects(Subject.objects.all())})
        if gform.is_valid():
            print gform.cleaned_data
            g.update(**gform.cleaned_data)
            return redirect("/group/id" + str(group_id))
    else:
        try:
            g = Group.objects.get(id=group_id)
        except:
            return render(request, "group_profile_fail.html", {"subjects": get_subjects(Subject.objects.all())})
        gform = GroupForm(initial={"name": g.name})
    return render(request, "group_edit.html", {"group_form": gform,
                                              "subjects": get_subjects(Subject.objects.all()),
                                              "group_id": group_id
                                             })